/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Client;

/**
 *
 * @author Asus
 */
//tes
import util.*;
import Server.Request;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class Peer {
  public String response;
  public static void main(String[] Args) {
    Peer cl = new Peer();
    Writer w;
    //InputStream in = new InputStream();
    //Reader r = new new InputStreamReader(in);
    Request tr = new Request("haha", 1, 1, 1, 1, "");
    String ret = cl.sendGetRequest("http://localhost:5000/", tr.getRequestString());
    //System.out.println("RET = " + ret);
  }

  /**
   * Sends an HTTP GET request to a url
   *
   * @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search")
   * @param requestParameters - all the request parameters (Example: "param1=val1&param2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself
   * @return - The response from the end point
   */
  public String sendGetRequest(String endpoint, String requestParameters) {
    String result = null;
    response = "";
//if (endpoint.startsWith("http://"))
//{
// Send a GET request to the servlet
    try {
      // Construct data
      StringBuffer data = new StringBuffer();

      // Send data
      String urlStr = endpoint;
      if (requestParameters != null && requestParameters.length() > 0) {
        urlStr += "?" + requestParameters;
      }
      URL url = new URL(urlStr);
      URLConnection conn = url.openConnection();
      conn.connect();

      // Get the response
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      StringBuffer sb = new StringBuffer();
      String line;

      while (!rd.ready()) {
        System.out.println("not ready!!");
      }
      //System.out.println(rd.readLine());

      while ((line = rd. readLine()) != null) {
        System.out.println(line);
        response = response + line + "\n";
        sb.append(line);
      }

      rd.close();
      result = sb.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }
//}
    return result;
  }

  /**
   * Re ads data from the data reader and posts it to a server via POST request.
   * data - The data you want to send
   * endpoint - The server's address
   * output - writes the server's response to output
   * @throws Exception
   */
  /*
  public static void postData(Reader data, URL endpoint, Writer output) throws Exception {
    HttpURLConnection urlc = null;
    try {
      urlc = (HttpURLConnection) endpoint.openConnection();
      try {
        urlc.setRequestMethod("POST");
      } catch (ProtocolException e) {
        throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
      }
      urlc.setDoOutput(true);
      urlc.setDoInput(true);
      urlc.setUseCaches(false);
      urlc.setAllowUserInteraction(false);
      urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");

      OutputStream out = urlc.getOutputStream();

      try {
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        pipe(data, writer);
        writer.close();
      } catch (IOException e) {
        throw new Exception("IOException while posting data", e);
      } finally {
        if (out != null) {
          out.close();
        }
      }

      InputStream in = urlc.getInputStream();
      try {
        Reader reader = new InputStreamReader(in);
        pipe(reader, output);
        reader.close();
      } catch (IOException e) {
        throw new Exception("IOException while reading response", e);
      } finally {
        if (in != null) {
          in.close();
        }
      }

    } catch (IOException e) {
      throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
      if (urlc != null) {
        urlc.disconnect();
      }
    }
  }
*/
  /**
   * Pipes everything from the reader to the writer via a buffer
   */
  private static void pipe(Reader reader, Writer writer) throws IOException {
    char[] buf = new char[1024];
    int read = 0;
    while ((read = reader.read(buf)) >= 0) {
      writer.write(buf, 0, read);
    }
    writer.flush();
  }

  public String GetHandshake(String FileName)
  {
//    Format handshake: <pstrlen><pstr><reserved><info_hash><peer_id>
//    Keterangan:
//    a. pstrlen: panjang dari string pstr, ditulis dalam byte. Panjang dari pstr adalah 19.
//    b. pstr: string identifier dari protokol. pstr = “BitTorrent protocol”.
//    c. reserved: reserved byte, dengan panjang 8 byte. Dapat diisikan dengan 8 buah byte 0.
//    d. info_hash: 20 byte SHA-1 dari nilai info pada file metainfo. Pada tugas ini, info_hash diganti dengan file_name. file_name adalah string dari nama file yang ingin di-download. file_name didapat dari info name pada file metainfo yang sudah di-hash dengan SHA-1 .
//    e. peer_id: 20-byte string yang merupakan ID dari client. (tidak perlu)
      int pstrlen=19;
      String pstr="BitTorrent protocol";
      String reserved="00000000";
      
      StringBuilder retval=new StringBuilder();
      retval.append("<"+String.valueOf(pstrlen)+">");
      retval.append("<"+pstr+">");
      retval.append("<"+reserved+">");
      retval.append("<"+helper.stringToHash(FileName)+">");
      return retval.toString();
  }

  public String GetPrefixMessage()
  {
//    Format length-prefixed message: <length prefix><message ID><payload>.
//    keep-alive: <len=0000>
//    choke: <len=0001><id=0>
//    unchoke: <len=0001><id=1>
//    interested: <len=0001><id=2>
//    not interested: <len=0001><id=3>
//    have: <len=0005><id=4><piece index>
//    bitfield: <len=0001+X><id=5><bitfield>
//    <len=0013><id=6><index><begin><length>
//    <len=0009+X><id=7><index><begin><block>
//    <len=0013><id=8><index><begin><length>

      StringBuilder retval=new StringBuilder();

      return retval.toString();
  }
}
